<?php

namespace app\admin\service\common\permission;

use app\common\Constants;
use think\facade\Log;

/**
 * 最大权限模式
 * 多个角色具有的数据权限，取最大权限
 */
class MaxDataPermissionResolver
{
    private const PRIORITY_MAP = [
        Constants::DATA_SCOPE_ALL => 6,
        Constants::DATA_SCOPE_DEPT_CUSTOM => 5,
        Constants::DATA_SCOPE_DEPT_AND_SUB => 4,
        Constants::DATA_SCOPE_DEPT_CURRENT => 3,
        Constants::DATA_SCOPE_SELF => 2,
        Constants::DATA_SCOPE_NONE => 1
    ];

    public function resolve(array $permissions): array
    {
        trace('max data permission resolution start', 'debug');

        $highestPriority = self::PRIORITY_MAP['NONE'];
        $selectedPermission = ['type' => 'NONE', 'custom_dept_ids' => []];
        $customDeptIds = [];

        foreach ($permissions as $perm) {
            $priority = self::PRIORITY_MAP[$perm['type']] ?? 0;

            // 收集所有自定义权限的部门ID
            if ($perm['type'] === 'DEPT_CUSTOM' && !empty($perm['custom_dept_ids'])) {
                $customDeptIds = array_merge($customDeptIds, $perm['custom_dept_ids']);
            }

            // 选择最高优先级权限
            if ($priority > $highestPriority) {
                $highestPriority = $priority;
                $selectedPermission = $perm;
            }
        }

        // 处理自定义部门ID合并
        if (!empty($customDeptIds)) {
            $selectedPermission['custom_dept_ids'] = array_values(array_unique($customDeptIds));
        }

        trace('数据权限：' . $selectedPermission['type'],'debug');

        return [
            'type' => $selectedPermission['type'],
            'custom_dept_ids' => $selectedPermission['custom_dept_ids'],
            'priority' => $highestPriority
        ];
    }
}